import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ad_feed_view.dart';
import 'package:flutter_hsh/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'junk_cleanup_logic.dart';

class JunkCleanupPage extends StatefulWidget {
  const JunkCleanupPage({Key? key}) : super(key: key);

  @override
  State<JunkCleanupPage> createState() => _JunkCleanupPageState();
}

class _JunkCleanupPageState extends State<JunkCleanupPage> {
  final JunkCleanupLogic controller = Get.put(JunkCleanupLogic());

  @override
  void initState() {
    super.initState();
    // 页面加载时自动开始扫描
    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.startScan();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      // 根据状态切换不同的页面与标题
      final isCleaning = controller.isCleaning.value;
      final showSuccess = controller.showSuccess.value;
      final titleText = isCleaning
          ? '一键清理'
          : '垃圾清理';

      return Scaffold(
        appBar: AppBar(
          title: Text(titleText),
          centerTitle: true,
          elevation: 0,
          backgroundColor: isCleaning ? Colors.blue : Colors.red,
          foregroundColor: Colors.white,
        ),
        body: () {
          if (isCleaning) {
            return _buildCleaningView();
          }
          if (showSuccess) {
            return _buildSuccessView();
          }
          if (controller.isScanning.value) {
            return _buildScanningView();
          } else if (controller.scanResults.isEmpty) {
            return _buildEmptyView();
          } else {
            return _buildResultsView();
          }
        }(),
        bottomNavigationBar: (!isCleaning && !showSuccess && controller.scanResults.isNotEmpty)
            ? _buildBottomActionBar()
            : null,
      );
    });
  }

  /// 构建扫描中的视图
  Widget _buildScanningView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
            strokeWidth: 4,
          ),
          const SizedBox(height: 24),
          Text(
            controller.scanStatus.value,
            style: const TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 8),
          const MyAdFeedView(),
          const SizedBox(height: 8),
          if (controller.scanProgress.value > 0)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 40),
              child: LinearProgressIndicator(
                value: controller.scanProgress.value,
                backgroundColor: Colors.grey[200],
                valueColor: const AlwaysStoppedAnimation<Color>(Colors.red),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建空结果视图
  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.check_circle,
            size: 80,
            color: Colors.green[400],
          ),
          const SizedBox(height: 16),
          const Text(
            '未发现垃圾文件',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '您的设备很干净',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 32),
          const MyAdFeedView(),
          const SizedBox(height: 8),
          ElevatedButton.icon(
            onPressed: controller.startScan,
            icon: const Icon(Icons.refresh),
            label: const Text('重新扫描'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建扫描结果视图
  Widget _buildResultsView() {
    return Column(
      children: [
        // 顶部统计信息
        _buildScanSummary(),
        
        // 垃圾文件列表
        Expanded(
          child: ListView.builder(
            itemCount: controller.scanResults.length,
            itemBuilder: (context, index) {
              final item = controller.scanResults[index];
              return _buildJunkItem(item, index);
            },
          ),
        ),
      ],
    );
  }

  /// 构建清理中的页面（参考截图蓝色背景与环形动画）
  Widget _buildCleaningView() {
    return Container(
      color: Colors.blue,
      width: double.infinity,
      height: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 使用圆形进度条表示清理进度
          SizedBox(
            width: 160,
            height: 160,
            child: CircularProgressIndicator(
              value: controller.cleaningProgress.value == 0
                  ? null // 未开始使用不确定进度动画
                  : controller.cleaningProgress.value,
              strokeWidth: 8,
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
              backgroundColor: Colors.white.withOpacity(0.2),
            ),
          ),
          const SizedBox(height: 24),
          // 显示释放空间数值（动态展示更具激励）
          Text(
            controller.lastFreedSize.value,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 36,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          const Text(
            '正在清理中',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建清理成功页面（参考截图：勾图标、提示文本、100分与释放空间提示）
  Widget _buildSuccessView() {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFB3E5FC), Color(0xFFE1F5FE)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      width: double.infinity,
      height: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.check_circle_outline,
            color: Colors.green,
            size: 58,
          ),
          const SizedBox(height: 16),
          const Text(
            '您的手机已经清理干净啦!',
            style: TextStyle(
              fontSize: 18,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 24),
          const Text(
            '100 分',
            style: TextStyle(
              fontSize: 36,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 12),
          Text(
            '释放空间：${controller.lastFreedSize.value}',
            style: const TextStyle(
              fontSize: 14,
              color: Colors.black54,
            ),
          ),
          const SizedBox(height: 32),
          // 返回按钮（也支持自动返回，见逻辑中的延时）
          ElevatedButton(
            onPressed: () async {
              controller.showSuccess.value = false;
              await controller.startScan();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            ),
            child: const Text('返回'),
          ),
        ],
      ),
    );
  }

  /// 构建扫描统计摘要
  Widget _buildScanSummary() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.red.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            Icons.delete_outline,
            size: 48,
            color: Colors.red[700],
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '发现垃圾文件',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.red[700],
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '${controller.scanResults.length} 个项目 • ${controller.getSelectedSize()}',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建单个垃圾文件项
  Widget _buildJunkItem(JunkItem item, int index) {
    if (index == 1){
      return Column(
        children: [
          const SizedBox(height: 8),
          const MyAdFeedView(),
          const SizedBox(height: 8),
          Card(
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
            child: ListTile(
              leading: Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  color: _getCategoryColor(item.category).withOpacity(0.2),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  _getCategoryIcon(item.category),
                  color: _getCategoryColor(item.category),
                  size: 24,
                ),
              ),
              title: Text(
                item.name,
                style: const TextStyle(fontWeight: FontWeight.w500),
              ),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(item.path),
                  const SizedBox(height: 2),
                  Text(
                    '${item.category} • ${item.size}',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
              trailing: Obx(() => Checkbox(
                value: controller.selectedItems[index],
                onChanged: (value) {
                  controller.toggleItemSelection(index, value ?? false);
                },
                activeColor: Colors.red,
              )),
              onTap: () {
                controller.toggleItemSelection(index, !controller.selectedItems[index]);
              },
            ),
          )
        ],
      );
    }
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: ListTile(
        leading: Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: _getCategoryColor(item.category).withOpacity(0.2),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            _getCategoryIcon(item.category),
            color: _getCategoryColor(item.category),
            size: 24,
          ),
        ),
        title: Text(
          item.name,
          style: const TextStyle(fontWeight: FontWeight.w500),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(item.path),
            const SizedBox(height: 2),
            Text(
              '${item.category} • ${item.size}',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
        trailing: Obx(() => Checkbox(
          value: controller.selectedItems[index],
          onChanged: (value) {
            controller.toggleItemSelection(index, value ?? false);
          },
          activeColor: Colors.red,
        )),
        onTap: () {
          controller.toggleItemSelection(index, !controller.selectedItems[index]);
        },
      ),
    );
  }

  /// 构建底部操作栏
  Widget _buildBottomActionBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: Row(
          children: [
            Obx(() => Checkbox(
              value: controller.isAllSelected.value,
              onChanged: (value) {
                controller.toggleAllSelection(value ?? false);
              },
              activeColor: Colors.red,
            )),
            const Text('全选'),
            const Spacer(),
            Obx(() {
              final selectedCount = controller.getSelectedCount();
              final selectedSize = controller.getSelectedSize();
              return Text(
                '已选 $selectedCount 项 • $selectedSize',
                style: const TextStyle(fontWeight: FontWeight.w500),
              );
            }),
            const SizedBox(width: 16),
            Obx(() => ElevatedButton(
              onPressed: controller.getSelectedCount() > 0
                  ? controller.startCleanup
                  : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: controller.isCleaning.value
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : const Text('一键清理'),
            )),
          ],
        ),
      ),
    );
  }

  /// 获取分类图标
  IconData _getCategoryIcon(String category) {
    switch (category) {
      case '缓存文件':
        return Icons.folder;
      case '临时文件':
        return Icons.schedule;
      case '日志文件':
        return Icons.description;
      case '广告缓存':
        return Icons.campaign;
      case '卸载残留':
        return Icons.delete_sweep;
      default:
        return Icons.help_outline;
    }
  }

  /// 获取分类颜色
  Color _getCategoryColor(String category) {
    switch (category) {
      case '缓存文件':
        return Colors.blue;
      case '临时文件':
        return Colors.orange;
      case '日志文件':
        return Colors.green;
      case '广告缓存':
        return Colors.purple;
      case '卸载残留':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }
}